package com.sunl.mall.trace.util;

import com.sunl.mall.common.util.DateUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TraceIdUtil {
    // 顺序生成id
    private static final Object lock = new Object();
    private static int index = 0;

    /**
     * id组成：yyyyMMddHHmmssSSSVVV
     *
     * @return
     */
    public static String genId() {
        StringBuilder sb = new StringBuilder(38);
        sb.append(LocalDateTime.now().format(DateUtil.DATE_FORMAT_1));// 17 chars
        String tmpIdx = "";
        synchronized (lock) {
            ++index;
            if (index > 999) {
                index = 0;
            }
            tmpIdx = String.format("%03d", index);
        }
        sb.append(tmpIdx);
        return sb.toString();
    }

    public static void main(String[] args) {
        List<String> ids = Collections.synchronizedList(new ArrayList<>());
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(40, 50, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10000));
        for (int i = 0; i < 9990; i++) {
            threadPoolExecutor.execute(() -> {
                String id = TraceIdUtil.genId();
                System.out.println("traceId: " + id);
                ids.add(id);
            });
        }
        threadPoolExecutor.shutdown();
        while (!threadPoolExecutor.isTerminated()) {
        }
        boolean b = ids.size() == ids.stream().distinct().count();
        System.out.println("重复: " + b);
        System.out.println("count: " + ids.size());
        System.out.println("ok");
    }
}
